﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LP
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DataSource dataSource;
        Graphs graphs;
        private BackgroundWorker bw = new BackgroundWorker();
        Loading loading;
        Boolean dataLoaded;

        // Construtor
        /// <summary>
        /// Constructor of MainWindow class
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            // Centrar a janela ao meio
            this.CenterWindowOnScreen();
            Application.Current.MainWindow.WindowState = WindowState.Maximized;

            // Inicializar a classe Graphs
            this.graphs = new Graphs();

            // Dados ainda não foram lidos, para que não seja possível clicar visualizar enquanto a leitura ocorre
            this.dataLoaded = false;

            // BackgroundWorker para a leitura de dados sem bloquear o programa
            bw.WorkerReportsProgress = false;
            bw.WorkerSupportsCancellation = false;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();

            // Mostrar a janela de Loading enquanto os dados são carregados (ler excel e escrever base de dados) 
            loading = new Loading();
            loading.Show();
        }

        // Centrar a janela ao meio
        /// <summary>
        /// Center MainWindow on screen
        /// </summary>
        private void CenterWindowOnScreen()
        {
            double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
            double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
            double windowWidth = this.Width;
            double windowHeight = this.Height;
            this.Left = (screenWidth / 2) - (windowWidth / 2);
            this.Top = (screenHeight / 2) - (windowHeight / 2);
        }

        // BackgroundWorker
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            this.dataSource = new DataSource();
        }

        // BackgroundWorker
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.dataBinding();
            this.dataLoaded = true;
            this.loading.Close();
        }

        // Ligação de dados para XAML
        /// <summary>
        /// Data binding to XAML 
        /// </summary>
        private void dataBinding()
        {
            // Target: Plot1 (Gráfico Oxyplot, ModelProperty)
            Binding MyBinding = new Binding();
            MyBinding.Source = this.graphs;
            MyBinding.Path = new PropertyPath("GraphsModel");
            MyBinding.Mode = BindingMode.OneWay;
            Plot1.SetBinding(OxyPlot.Wpf.PlotView.ModelProperty, MyBinding);

            // Target: GraphType (Tipo de gráfico, ItemsSourceProperty)
            Binding MyBinding1 = new Binding();
            MyBinding1.Source = this.dataSource;
            MyBinding1.Path = new PropertyPath("GraphTypeList");
            MyBinding1.Mode = BindingMode.OneWay;
            GraphType.SetBinding(ComboBox.ItemsSourceProperty, MyBinding1);

            // Target: DataListBox (Lista tipo de dados, ItemsSourceProperty)
            Binding MyBinding2 = new Binding();
            MyBinding2.Source = this.dataSource;
            MyBinding2.Path = new PropertyPath("DataList");
            MyBinding2.Mode = BindingMode.TwoWay;
            DataListBox.SetBinding(ListBox.ItemsSourceProperty, MyBinding2);

            // Target: FromYear (Ano inicial, ItemsSourceProperty)
            Binding MyBinding3 = new Binding();
            MyBinding3.Source = this.dataSource;
            MyBinding3.Path = new PropertyPath("FromYearList");
            MyBinding3.Mode = BindingMode.TwoWay;
            FromYear.SetBinding(ComboBox.ItemsSourceProperty, MyBinding3);

            // Target: ToYear (Ano final, ItemsSourceProperty)
            Binding MyBinding4 = new Binding();
            MyBinding4.Source = this.dataSource;
            MyBinding4.Path = new PropertyPath("ToYearList");
            MyBinding4.Mode = BindingMode.TwoWay;
            ToYear.SetBinding(ComboBox.ItemsSourceProperty, MyBinding4);

            // Target: ToYear (Ano final, SelectedIndexProperty)
            Binding MyBinding5 = new Binding();
            MyBinding5.Source = this.dataSource;
            MyBinding5.Path = new PropertyPath("SelectedIndex");
            MyBinding5.Mode = BindingMode.TwoWay;
            ToYear.SetBinding(ComboBox.SelectedIndexProperty, MyBinding5);

            // Target: FromYear (Ano inicial, SelectedItemProperty)
            Binding MyBinding6 = new Binding();
            MyBinding6.Source = this.dataSource;
            MyBinding6.Path = new PropertyPath("FromYear");
            MyBinding6.Mode = BindingMode.TwoWay;
            FromYear.SetBinding(ComboBox.SelectedItemProperty, MyBinding6);

            // Target: ToYear (Ano final, SelectedItemProperty)
            Binding MyBinding7 = new Binding();
            MyBinding7.Source = this.dataSource;
            MyBinding7.Path = new PropertyPath("ToYear");
            MyBinding7.Mode = BindingMode.TwoWay;
            ToYear.SetBinding(ComboBox.SelectedItemProperty, MyBinding7);
        }

        // Ao clicar: "Visualizar Gráfico"
        /// <summary>
        /// Shows graphs with selected data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Se pelo menos algum dado estiver selecionado
            if (this.dataLoaded && (this.dataSource.getSelectedDataNames().Count > 0))
            {
                if (GraphType.SelectedItem.ToString().Equals("Linhas"))
                    this.graphs.MultipleLineChart(this.dataSource.getData(), "Gráfico", this.dataSource.FromYear, this.dataSource.ToYear, "Ano", "Valor", this.dataSource.getSelectedDataNames());
                if (GraphType.SelectedItem.ToString().Equals("Barras"))
                    this.graphs.MultipleBarChart(this.dataSource.getData(), "Gráfico", this.dataSource.FromYear, this.dataSource.ToYear, "Ano", "Valor", this.dataSource.getSelectedDataNames());
                if (GraphType.SelectedItem.ToString().Equals("Dispersão"))
                    this.graphs.MultipleScatterChart(this.dataSource.getData(), "Gráfico", this.dataSource.FromYear, this.dataSource.ToYear, "Ano", "Valor", this.dataSource.getSelectedDataNames());

                this.Plot1.InvalidatePlot(true);
            }
        }

        // Ao selecionar "Desde o ano:"
        /// <summary>
        /// Updates the ComboBox "FromYear"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FromYear_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.dataSource.updateFinalYears();
        }

        /// <summary>
        /// Shows save file (PDF) dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Gráfico"; // Default file name
            dlg.DefaultExt = ".pdf"; // Default file extension
            dlg.Filter = "Arquivos Adobe PDF (*.pdf)|*.pdf"; // Filter files by extension

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                string filename = dlg.FileName;
                this.graphs.exportPDF(filename);
            }
        }

        /// <summary>
        /// Shows save file (SVG) dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Gráfico"; // Default file name
            dlg.DefaultExt = ".svg"; // Default file extension
            dlg.Filter = "SVG (*.svg)|*.svg"; // Filter files by extension

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                string filename = dlg.FileName;
                this.graphs.exportSVG(filename);
            }
        }
        
        /// <summary>
        /// Closes the application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        /// <summary>
        /// Opens window with graph shorcuts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            GraphsHelp ghelp = new GraphsHelp();
            ghelp.Show();
        }

        /// <summary>
        /// Opens window with about
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Click_4(object sender, RoutedEventArgs e)
        {
            About about = new About();
            about.Show();
        }
    }

}
